package br.ufrn.btest.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import br.ufrn.btest.parser.Machine;
import br.ufrn.btest.parser.Operation;
import br.ufrn.btest.view.Application;
import br.ufrn.btest.view.ExtensionFileFilter;
import de.be4.classicalb.core.parser.BException;

public class LoadMachineAction extends AbstractAction{

	private Application application;
	
	public LoadMachineAction(Application application) {
		this.application = application;
		putValue(NAME, "Load Machine");
		putValue(SHORT_DESCRIPTION, "Some short description");
	}
	
	public void actionPerformed(ActionEvent e) {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileFilter(new ExtensionFileFilter("B Machines", "mch"));
		int response = fileChooser.showOpenDialog(application.getfrmBtest());
		
		if(response == JFileChooser.APPROVE_OPTION) {
			File mch = fileChooser.getSelectedFile();
			
			try {
				application.setMachine(new Machine(mch));
				
				String machineName = application.getMachine().getName();
				application.getLabelMachineLoaded().setText("Machine Loaded: " + machineName);
				
				List<Operation> operations = application.getMachine().getOperations();
				
				DefaultListModel listModel = new DefaultListModel();
				
				int indexCount = 0;
				for (Operation op : operations) {
					listModel.add(indexCount, op.getName());
					indexCount ++;
				}
				
				application.getOperationList().setModel(listModel);
				application.getOperationList().validate();
			} catch (BException e1) {
				String machineWithErrorsMsg = "The machine you are trying to load contains the following specification errors: \n\n" +
												e1.getMessage() + "\n\n" +
												"Fix it and try to load it again.";
				JOptionPane.showMessageDialog(null, machineWithErrorsMsg, "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}
	
}
